package com.example.demomk.Utils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Interpolator;
import android.graphics.drawable.ColorDrawable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.demomk.Interface.OnDialogButtonClickListener;
import com.example.demomk.ViewModel.MeasurementViewModel;
import com.example.demomk.databinding.DialogCustomBinding;
import com.example.demomk.databinding.DialogStdBinding;
import com.example.demomk.entity.AvgMeasurement;
import com.example.demomk.entity.Measurement;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StdDialog extends Dialog {
    private OnDialogButtonClickListener listener;
    private  DialogStdBinding binding;
    private TextView start,end;
    private String message;
    private MeasurementViewModel  viewModel;
    private final FragmentActivity fragmentActivity;
    private int start_id;

    private TextView title;
    private Spinner spinnerTitle, spinnerAir,  spinnerLevel, spinnerMaxSize, spinnerStatus;
    public StdDialog(@NonNull Context context, @Nullable OnDialogButtonClickListener listener,@NonNull FragmentActivity activity,  int startId) {
        super(context);
        this.listener = listener;
        this.fragmentActivity = activity;
        this.start_id = startId;

        initView();
    }
//    public StdDialog(@NonNull Context context, int themeResId) {
//        super(context, themeResId);
//    }

    @Deprecated
    public StdDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        throw new UnsupportedOperationException("请使用带 FragmentActivity 的构造函数");
    }
    private void initView() {
        // 设置自定义布局
        binding = DialogStdBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        title = binding.etTitle;
        //下拉框
        spinnerTitle = binding.spinnerIP;
        spinnerAir = binding.Air;
        spinnerLevel = binding.level;
        spinnerMaxSize = binding.maxSize;
        spinnerStatus = binding.status;

        //数据范围
        start = binding.startPage;
        end = binding.endPage;

        viewModel = new ViewModelProvider(fragmentActivity).get(MeasurementViewModel.class);

        viewModel.getAvgMeasurementWithDetails(start_id).observe(fragmentActivity, avg -> {
            if (avg != null) {
                List<Integer> ids = new ArrayList<>();
                for (Measurement mes : avg.measurements) {
                    ids.add(mes.getId());
                }
                //输出ids
                start.setText(String.valueOf(ids.get(0)));
                end.setText(String.valueOf(ids.get(ids.size() - 1)));
            }
        });

        // 设置点击外部可取消
        setCancelable(true);//用户点击返回键时
        setCanceledOnTouchOutside(false);//点击对话框外部区域

        binding.btnConfirm.setOnClickListener(v -> {

            String titles = title.getText().toString().trim();
            if (!TextUtils.isEmpty(titles)) {
                // 非空，执行操作
                dismiss();

            } else {
                Toast.makeText(fragmentActivity, "报告标题不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            // 构造数据对象
            StdDialogData data = new StdDialogData(
                    titles,
                    spinnerTitle.getSelectedItem().toString(),
                    spinnerAir.getSelectedItem().toString(),
                    spinnerLevel.getSelectedItem().toString(),
                    spinnerMaxSize.getSelectedItem().toString(),
                    spinnerStatus.getSelectedItem().toString()
            );

            // 确认按钮点击事件
            if (listener != null) {
                listener.onCancel(start_id, 2,titles,data);
            }
        });

        // 设置窗口属性
        Window window = getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            // 关键修改：添加以下标志
            // 获取屏幕宽度
            DisplayMetrics metrics = new DisplayMetrics();
            window.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int screenWidth = metrics.widthPixels;

            //修改屏幕高度
            int screenHeight = metrics.heightPixels;

            // 设置对话框宽度为屏幕宽度的90%
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (screenWidth * 0.9);
//            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.height = (int) (screenHeight * 0.85);
            params.dimAmount = 0.2f;
            window.setAttributes(params);
        }

        //点击关闭按钮
        binding.ivClose.setOnClickListener(v -> {
            dismiss();
        });
    }


}
